﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using MyShop.Models;
using Lucene.Net.Analysis;
using System.IO;
using Lucene.Net.Analysis.PanGu;

namespace MyShop.PublicMethod
{
    public class CustomMethod
    {

        private static string reg = @"<body>[\S\s]*?</body>";
        /// <summary>
        /// 将对象序列化成json   JavaScriptSerializer  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string ModelToJson(Object obj)
        {
            String str = "";
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            return str;
        }
        /// <summary>
        /// json反序列成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public T ScriptDeserialize<T>(string strJson)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(strJson);
        }
        /// <summary>
        /// 反序列化成数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public List<T> JSONStringToList<T>(string strJson)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<T> objList = serializer.Deserialize<List<T>>(strJson);
            return objList;
        }

        /// <summary>
        /// 对keyword进行分词，将分词的结果返回
        /// </summary>
        public static List<string> SplitWords(string keyword)
        {
            List<string> list = new List<string>();
            Analyzer analyzer = new PanGuAnalyzer();
            TokenStream tokenStream = analyzer.TokenStream("", new StringReader(keyword));
            Token token = null;

            while ((token = tokenStream.Next()) != null)
            {
                // token.TermText()为当前分的词
                string word = token.TermText();
                list.Add(word);
            }

            return list;
        }

        /// <summary>
        /// 将搜索词拆分 并检索
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        public string GetKeyWords(string keyWord)
        {
            var list = SplitWords(keyWord);
            //string result = "";
            //string html = GetHtmlByHttpHelper(keyWord);
            //if (string.IsNullOrEmpty(html) || html=="操作超时")
            //{
            //    return keyWord;
            //}

            //var item = ScriptDeserialize<KeyWords>(html);

            //var ret = (object[])item.words;
            var result = list[0].ToString();
            for (int index = 1; index < list.Count; index++)
            {
                result += "|" + list[index].ToString();

            }
            return result;
        }
        public static List<string> GetInfoByRegex(string regexStr, string htmlText, int index)
        {
            try
            {
                List<string> infoList = new List<string>();
                Regex regResource = new Regex(regexStr, RegexOptions.IgnoreCase);
                MatchCollection mResource = regResource.Matches(htmlText);

                foreach (Match itemhtmlText in mResource)
                {
                    infoList.Add(itemhtmlText.Groups[index].ToString());
                    if (infoList.Count == 18)
                    {
                        break;
                    }
                }
                return infoList;
            }
            catch (Exception ex)
            {
                // WriteLog("GetInfoByRegex:" + ex.Message.ToString());
                return null;
            }
        }

        /// <summary>
        /// 使用 httphelper类通过url获取html
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string GetHtmlByHttpHelper(string keyWord)
        {
            try
            {
                string par = "{" + keyWord +
                "}";
                string url = string.Format("https://api.prprpr.me/emotion?text={0}", par);
                //创建Httphelper对象
                HttpHelper http = new HttpHelper();
                //创建Httphelper参数对象
                HttpItem item = new HttpItem()
                {
                    URL = url,//URL     必需项    
                    Method = "get",//URL     可选项 默认为Get   
                    ContentType = "text/html",//返回类型    可选项有默认值   
                    Timeout = 5000,//设置超时
                    // ProxyIp = iplist[index],
                    Allowautoredirect = true
                    //ContentType = "application/x-www-form-urlencoded",//返回类型    可选项有默认值   
                };
                //请求的返回值对象
                HttpResult result = http.GetHtml(item);
                //获取请请求的Html
                string html = result.Html;
                return html;

            }
            catch (Exception ex)
            {
                // WriteLog("GetHtmlByHttpHelper " + ex.Message.ToString() + ":" + url);
                return keyWord;
            }
        }
    }
}